<?php
require_once 'mydb.php';
 
$con = new MyDB();

$action =  $_GET['action'];
$uniqueID = $_GET['uniqueID'];
$phoneNumber = $_GET['phoneNumber'];
$authenticationCode = $_GET['authenticationCode'];
	
if ( $action == "AUTHENTICATION" ) {
	
	$query = $con -> selectFrom("users", $columns = array('uniqueID','phoneNumber'), $where = array('uniqueID'=>$uniqueID), $like = false, $orderby = 
"uniqueID", $direction = "DESC", $limit = null, $offset = null);

	if ( $query['uniqueID'] == $uniqueID ) {
		$json = '{"authenticated":false}';
	} else { 
		$json = '{"authenticated":true}';
	}
} elseif ( $action == "SENDSMS" ) {
		$authCode = getAuthenticationCode();
		$query = $con -> deleteFrom("users", $where = array('uniqueID'=>$uniqueID), $like = false, $limit = 1);
		$query = $con -> insertInto("users", $fields = array("uniqueID" => $uniqueID, "phoneNumber" => $phoneNumber, "authCode" => $authCode, "authenticated" 
=> false));	 
		$json = '{"hassent":true, "authenticationCode":'.$authCode.'}';
} elseif ( $action == "CREATEACCOUNT" ) {

	$query = $con -> selectFrom("users", $columns = array('uniqueID','phoneNumber'), $where = array('uniqueID'=>"$uniqueID", 'authCode' => "
$authenticationCode"), $like = false, $orderby = "uniqueID", $direction = "DESC", $limit = null, $offset = null);

	if ( $query.id == 0 ) { 
		$json = '{"hascreated":false, "uniqueID":$query.id}';
	} else { 
		$query = $con -> updateTable("users", $fields = array("authenticated" => true), $where = array("uniqueID"=>"$uniqueID"), $like = true);
		$json = '{"hascreated":true, "uniqueID":$query.id}';
	}	
}

echo $json;

function getAuthenticationCode() {
	return mt_rand(10000000, 99999999);
}
?>